<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} 
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  欢迎使用本系统
                </div>
              </div>
            </div>
          </el-col>

        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">

    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" class="h-full">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.shortcutOperation') }}</span>
            <el-link
              type="primary"
              :underline="false"
              href="https://gitee.com/liyou_hachimi/medical_vue3_web.git"
              target="_blank"
            >
              {{ t('action.more') }}
            </el-link>
          </div>
        </template>

        <!--这里是内容-->
        
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" >
                <el-card shadow="hover" class="mb-8px cursor-pointer" @click="goToRegister">
                  <el-skeleton :loading="loading" animated>
                    用户挂号
                  </el-skeleton>
                </el-card>
            </el-col>
            <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px cursor-pointer" @click="goToRating">
                <el-skeleton :loading="loading" animated>
                    就诊记录
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>

        </el-skeleton>
      

        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col v-for="item in shortcut" :key="`team-${item.name}`" :span="8" class="mb-8px">
              <div class="flex items-center">
                <Icon :icon="item.icon" class="mr-8px" />
                <el-link type="default" :underline="false">
                  {{ item.name }}
                </el-link>
              </div>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
      
    </el-col>


    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" class="h-full">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.notice') }}</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <div v-for="(item, index) in notice" :key="`dynamics-${index}`">
            <div class="flex items-center">
              <el-avatar :size="35" class="mr-16px">
                <img src="@/assets/imgs/tip.png" alt="" />
              </el-avatar>
              <div>
                <div class="text-14px">
                  <Highlight :keys="item.keys.map((v) => t(v))">
                    {{ item.type }} : {{ item.title }}
                  </Highlight>
                </div>
                
              </div>
            </div>
            <el-divider />
          </div>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>

    <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>科室与医师信息</span>
            <el-link
              type="primary"
              :underline="false"
              href="https://gitee.com/liyou_hachimi/medical_vue3_web.git"
              target="_blank"
            >
              {{ t('action.more') }}
            </el-link>
          </div>
        </template>

        <el-row :gutter="16" justify="space-between" class="mt-16px">
          

        <el-col :span="4" :xs="4">
          <ContentWrap class="h-1/1">
            <MedicalDeptTree @node-click="handleDeptNodeClick" />
          </ContentWrap>
        </el-col>
        
        <el-col :span="20" :xs="20">
          <ContentWrap class="h-1/1">
            <el-table :data="state.doctorList" border stripe v-loading="state.loading">
              <el-table-column prop="nickname" label="医师姓名" width="120" />
              <el-table-column prop="sex" label="性别" width="80">
                  <template #default="{row}">
                    {{ getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX).find(item => item.value === row.sex)?.label }}
                  </template>
              </el-table-column>

               <el-table-column label="肖像" width="100">
                <template #default="{row}">
                  <el-image
                    :src="row.avatar"
                    style="width: 60px; height: 60px"
                    :preview-src-list="[row.avatar]"
                    fit="cover"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="doctorType" label="医师类型" width="120"/>
              <el-table-column prop="cost" label="挂号费" width="120" />
              <el-table-column prop="remark" label="医师介绍" />

              <el-table-column prop="workYears" label="工作年限" width="120" />
            </el-table>
          </ContentWrap>
        </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DoctorApi from '@/api/medical/doctor'
import MedicalDeptTree from './MedicalDeptTree.vue'
import { useUserStore } from '@/store/modules/user'
import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'
import { useRouter } from 'vue-router'

defineOptions({ name: 'Home' })

const { t } = useI18n()
const message = useMessage()
const router = useRouter()
const userStore = useUserStore()
const { setWatermark } = useWatermark()
const loading = ref(true)

const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const queryParams = reactive({
  deptId: undefined, // 科室ID
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    
  ]
  projects = Object.assign(projects, data)
}

// 获取通知公告
let notice = reactive<Notice[]>([])
const getNotice = async () => {
  const data = [
    {
      title: '用户可以在就诊反馈处简单评价医生',
      type: '提示',
      keys: [],
      date: new Date()
    },
    {
      title: '点击左侧更多可以查看Gitee的源代码',
      type: '提示',
      keys: ['左侧', '源代码'],
      date: new Date()
    },
  ]
  notice = Object.assign(notice, data)
}

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    
  ]
  shortcut = Object.assign(shortcut, data)
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const goToRegister = () => {
  router.push('medical/user/userRegister')
}

const goToRating = () => {
  router.push('medical/user/userRating') 
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    getNotice(),
    getShortcut(),
    getUserAccessSource(),
    getWeeklyUserActivity()
  ])
  loading.value = false
}

const handleProjectClick = (message: string) => {
  window.open(`https://${message}`, '_blank')
}

const handleShortcutClick = (url: string) => {
  router.push(url)
}

// 定义状态对象
const state = reactive({
  doctorList: [] as any[],
  visible: false,
  loading: false
})

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  const deptId = row.id
  state.visible = true
  state.loading = true
  try {
    console.log('请求参数:', { deptId }); // 打印请求参数
    const response = await DoctorApi.getDoctorInDept(deptId)
    state.doctorList = response
    message.success(`已加载该科室下${response.length}位医师`)
  } catch (error) {
    console.error('获取医师列表失败详情:', {
      error
    });
    console.error('获取医师列表失败:', error)
    message.error('获取医师列表失败')
  } finally {
    state.loading = false
  }
}

getAllApi()
</script>
